home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 1.iso / util / tgrep20.zip / GETOPT.C < prev    next >
Text File  |  1994-03-29  |  19KB  |  648 lines

  1. /* Getopt for GNU.
  2.    NOTE: getopt is now part of the C library, so if you don't know what
  3.    "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
  4.    before changing it!
  5.  
  6.    Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
  7.        Free Software Foundation, Inc.
  8.  
  9.    This program is free software; you can redistribute it and/or modify it
  10.    under the terms of the GNU General Public License as published by the
  11.    Free Software Foundation; either version 2, or (at your option) any
  12.    later version.
  13.  
  14.    This program is distributed in the hope that it will be useful,
  15.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  16.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17.    GNU General Public License for more details.
  18.  
  19.    You should have received a copy of the GNU General Public License
  20.    along with this program; if not, write to the Free Software
  21.    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  22.  
  23. #include <malloc.h>
  24. #include <stdio.h>
  25. #include <stdlib.h>
  26. #include "getopt.h"
  27.  
  28. /* For communication from `getopt' to the caller.
  29.    When `getopt' finds an option that takes an argument,
  30.    the argument value is returned here.
  31.    Also, when `ordering' is RETURN_IN_ORDER,
  32.    each non-option ARGV-element is returned here.  */
  33.  
  34. char *optarg = 0;
  35.  
  36. /* Index in ARGV of the next element to be scanned.
  37.    This is used for communication to and from the caller
  38.    and for communication between successive calls to `getopt'.
  39.  
  40.    On entry to `getopt', zero means this is the first call; initialize.
  41.  
  42.    When `getopt' returns EOF, this is the index of the first of the
  43.    non-option elements that the caller should itself scan.
  44.  
  45.    Otherwise, `optind' communicates from one call to the next
  46.    how much of ARGV has been scanned so far.  */
  47.  
  48. /* XXX 1003.2 says this must be 1 before any call.  */
  49. int optind = 0;
  50.  
  51. /* The next char to be scanned in the option-element
  52.    in which the last option character we returned was found.
  53.    This allows us to pick up the scan where we left off.
  54.  
  55.    If this is zero, or a null string, it means resume the scan
  56.    by advancing to the next ARGV-element.  */
  57.  
  58. static char *nextchar;
  59.  
  60. /* Callers store zero here to inhibit the error message
  61.    for unrecognized options.  */
  62.  
  63. int opterr = 1;
  64.  
  65. /* Set to an option character which was unrecognized.
  66.    This must be initialized on some systems to avoid linking in the
  67.    system's own getopt implementation.  */
  68.  
  69. int optopt = '?';
  70.  
  71. /* Describe how to deal with options that follow non-option ARGV-elements.
  72.  
  73.    If the caller did not specify anything,
  74.    the default is REQUIRE_ORDER if the environment variable
  75.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  76.  
  77.    REQUIRE_ORDER means don't recognize them as options;
  78.    stop option processing when the first non-option is seen.
  79.    This is what Unix does.
  80.    This mode of operation is selected by either setting the environment
  81.    variable POSIXLY_CORRECT, or using `+' as the first character
  82.    of the list of option characters.
  83.  
  84.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  85.    so that eventually all the non-options are at the end.  This allows options
  86.    to be given in any order, even with programs that were not written to
  87.    expect this.
  88.  
  89.    RETURN_IN_ORDER is an option available to programs that were written
  90.    to expect options and other ARGV-elements in any order and that care about
  91.    the ordering of the two.  We describe each non-option ARGV-element
  92.    as if it were the argument of an option with character code 1.
  93.    Using `-' as the first character of the list of option characters
  94.    selects this mode of operation.
  95.  
  96.    The special argument `--' forces an end of option-scanning regardless
  97.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  98.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  99.  
  100. #include <string.h>
  101. static enum
  102. {
  103.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  104. } ordering;
  105.  
  106. /* Avoid depending on library functions or files
  107.    whose names are inconsistent.  */
  108.  
  109. char *getenv ();
  110.  
  111. static char *
  112. my_index (
  113.      const char *str,
  114.      int chr)
  115. {
  116.   while (*str)
  117.     {
  118.       if (*str == chr)
  119.     return (char *) str;
  120.       str++;
  121.     }
  122.   return 0;
  123. }
  124.  
  125. static void
  126. my_bcopy (
  127.      const char *from,
  128.      char *to,
  129.      int size)
  130. {
  131.   int i;
  132.   for (i = 0; i < size; i++)
  133.     to[i] = from[i];
  134. }
  135. /* Handle permutation of arguments.  */
  136.  
  137. /* Describe the part of ARGV that contains non-options that have
  138.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  139.    `last_nonopt' is the index after the last of them.  */
  140.  
  141. static int first_nonopt;
  142. static int last_nonopt;
  143.  
  144. /* Exchange two adjacent subsequences of ARGV.
  145.    One subsequence is elements [first_nonopt,last_nonopt)
  146.    which contains all the non-options that have been skipped so far.
  147.    The other is elements [last_nonopt,optind), which contains all
  148.    the options processed since those non-options were skipped.
  149.  
  150.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  151.    the new indices of the non-options in ARGV after they are moved.  */
  152.  
  153. static void
  154. exchange (
  155.      char **argv)
  156. {
  157.   int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
  158.   char **temp = (char **) alloca (nonopts_size);
  159.  
  160.   /* Interchange the two blocks of data in ARGV.  */
  161.  
  162.   my_bcopy ((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
  163.   my_bcopy ((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
  164.         (optind - last_nonopt) * sizeof (char *));
  165.   my_bcopy ((char *) temp,
  166.         (char *) &argv[first_nonopt + optind - last_nonopt],
  167.         nonopts_size);
  168.  
  169.   /* Update records for the slots the non-options now occupy.  */
  170.  
  171.   first_nonopt += (optind - last_nonopt);
  172.   last_nonopt = optind;
  173. }
  174.  
  175. /* Scan elements of ARGV (whose length is ARGC) for option characters
  176.    given in OPTSTRING.
  177.  
  178.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  179.    then it is an option element.  The characters of this element
  180.    (aside from the initial '-') are option characters.  If `getopt'
  181.    is called repeatedly, it returns successively each of the option characters
  182.    from each of the option elements.
  183.  
  184.    If `getopt' finds another option character, it returns that character,
  185.    updating `optind' and `nextchar' so that the next call to `getopt' can
  186.    resume the scan with the following option character or ARGV-element.
  187.  
  188.    If there are no more option characters, `getopt' returns `EOF'.
  189.    Then `optind' is the index in ARGV of the first ARGV-element
  190.    that is not an option.  (The ARGV-elements have been permuted
  191.    so that those that are not options now come last.)
  192.  
  193.    OPTSTRING is a string containing the legitimate option characters.
  194.    If an option character is seen that is not listed in OPTSTRING,
  195.    return '?' after printing an error message.  If you set `opterr' to
  196.    zero, the error message is suppressed but we still return '?'.
  197.  
  198.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  199.    so the following text in the same ARGV-element, or the text of the following
  200.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  201.    wants an optional arg; if there is text in the current ARGV-element,
  202.    it is returned in `optarg', otherwise `optarg' is set to zero.
  203.  
  204.    If OPTSTRING starts with `-' or `+', it requests different methods of
  205.    handling the non-option ARGV-elements.
  206.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  207.  
  208.    Long-named options begin with `--' instead of `-'.
  209.    Their names may be abbreviated as long as the abbreviation is unique
  210.    or is an exact match for some defined option.  If they have an
  211.    argument, it follows the option name in the same ARGV-element, separated
  212.    from the option name by a `=', or else the in next ARGV-element.
  213.    When `getopt' finds a long-named option, it returns 0 if that option's
  214.    `flag' field is nonzero, the value of the option's `val' field
  215.    if the `flag' field is zero.
  216.  
  217.    The elements of ARGV aren't really const, because we permute them.
  218.    But we pretend they're const in the prototype to be compatible
  219.    with other systems.
  220.  
  221.    LONGOPTS is a vector of `struct option' terminated by an
  222.    element containing a name which is zero.
  223.  
  224.    LONGIND returns the index in LONGOPT of the long-named option found.
  225.    It is only valid when a long-named option has been found by the most
  226.    recent call.
  227.  
  228.    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
  229.    long-named options.  */
  230.  
  231. int
  232. _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
  233.      int argc;
  234.      char *const *argv;
  235.      const char *optstring;
  236.      const struct option *longopts;
  237.      int *longind;
  238.      int long_only;
  239. {
  240.   int option_index;
  241.  
  242.   optarg = 0;
  243.  
  244.   /* Initialize the internal data when the first call is made.
  245.      Start processing options with ARGV-element 1 (since ARGV-element 0
  246.      is the program name); the sequence of previously skipped
  247.      non-option ARGV-elements is empty.  */
  248.  
  249.   if (optind == 0)
  250.     {
  251.       first_nonopt = last_nonopt = optind = 1;
  252.  
  253.       nextchar = NULL;
  254.  
  255.       /* Determine how to handle the ordering of options and nonoptions.  */
  256.  
  257.       if (optstring[0] == '-')
  258.     {
  259.       ordering = RETURN_IN_ORDER;
  260.       ++optstring;
  261.     }
  262.       else if (optstring[0] == '+')
  263.     {
  264.       ordering = REQUIRE_ORDER;
  265.       ++optstring;
  266.     }
  267.       else if (getenv ("POSIXLY_CORRECT") != NULL)
  268.     ordering = REQUIRE_ORDER;
  269.       else
  270.     ordering = PERMUTE;
  271.     }
  272.  
  273.   if (nextchar == NULL || *nextchar == '\0')
  274.     {
  275.       if (ordering == PERMUTE)
  276.     {
  277.       /* If we have just processed some options following some non-options,
  278.          exchange them so that the options come first.  */
  279.  
  280.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  281.         exchange ((char **) argv);
  282.       else if (last_nonopt != optind)
  283.         first_nonopt = optind;
  284.  
  285.       /* Now skip any additional non-options
  286.          and extend the range of non-options previously skipped.  */
  287.  
  288.       while (optind < argc
  289.          && (argv[optind][0] != '-' || argv[optind][1] == '\0')
  290. #ifdef GETOPT_COMPAT
  291.          && (longopts == NULL
  292.              || argv[optind][0] != '+' || argv[optind][1] == '\0')
  293. #endif                /* GETOPT_COMPAT */
  294.          )
  295.         optind++;
  296.       last_nonopt = optind;
  297.     }
  298.  
  299.       /* Special ARGV-element `--' means premature end of options.
  300.      Skip it like a null option,
  301.      then exchange with previous non-options as if it were an option,
  302.      then skip everything else like a non-option.  */
  303.  
  304.       if (optind != argc && !strcmp (argv[optind], "--"))
  305.     {
  306.       optind++;
  307.  
  308.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  309.         exchange ((char **) argv);
  310.       else if (first_nonopt == last_nonopt)
  311.         first_nonopt = optind;
  312.       last_nonopt = argc;
  313.  
  314.       optind = argc;
  315.     }
  316.  
  317.       /* If we have done all the ARGV-elements, stop the scan
  318.      and back over any non-options that we skipped and permuted.  */
  319.  
  320.       if (optind == argc)
  321.     {
  322.       /* Set the next-arg-index to point at the non-options
  323.          that we previously skipped, so the caller will digest them.  */
  324.       if (first_nonopt != last_nonopt)
  325.         optind = first_nonopt;
  326.       return EOF;
  327.     }
  328.  
  329.       /* If we have come to a non-option and did not permute it,
  330.      either stop the scan or describe it to the caller and pass it by.  */
  331.  
  332.       if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
  333. #ifdef GETOPT_COMPAT
  334.       && (longopts == NULL
  335.           || argv[optind][0] != '+' || argv[optind][1] == '\0')
  336. #endif                /* GETOPT_COMPAT */
  337.       )
  338.     {
  339.       if (ordering == REQUIRE_ORDER)
  340.         return EOF;
  341.       optarg = argv[optind++];
  342.       return 1;
  343.     }
  344.  
  345.       /* We have found another option-ARGV-element.
  346.      Start decoding its characters.  */
  347.  
  348.       nextchar = (argv[optind] + 1
  349.           + (longopts != NULL && argv[optind][1] == '-'));
  350.     }
  351.  
  352.   if (longopts != NULL
  353.       && ((argv[optind][0] == '-'
  354.        && (argv[optind][1] == '-' || long_only))
  355. #ifdef GETOPT_COMPAT
  356.       || argv[optind][0] == '+'
  357. #endif                /* GETOPT_COMPAT */
  358.       ))
  359.     {
  360.       const struct option *p;
  361.       char *s = nextchar;
  362.       int exact = 0;
  363.       int ambig = 0;
  364.       const struct option *pfound = NULL;
  365.       int indfound;
  366.  
  367.       while (*s && *s != '=')
  368.     s++;
  369.  
  370.       /* Test all options for either exact match or abbreviated matches.  */
  371.       for (p = longopts, option_index = 0; p->name;
  372.        p++, option_index++)
  373.     if (!strncmp (p->name, nextchar, s - nextchar))
  374.       {
  375.         if (s - nextchar == strlen (p->name))
  376.           {
  377.         /* Exact match found.  */
  378.         pfound = p;
  379.         indfound = option_index;
  380.         exact = 1;
  381.         break;
  382.           }
  383.         else if (pfound == NULL)
  384.           {
  385.         /* First nonexact match found.  */
  386.         pfound = p;
  387.         indfound = option_index;
  388.           }
  389.         else
  390.           /* Second nonexact match found.  */
  391.           ambig = 1;
  392.       }
  393.  
  394.       if (ambig && !exact)
  395.     {
  396.       if (opterr)
  397.         fprintf (stderr, "%s: option `%s' is ambiguous\n",
  398.              argv[0], argv[optind]);
  399.       nextchar += strlen (nextchar);
  400.       optind++;
  401.       return '?';
  402.     }
  403.  
  404.       if (pfound != NULL)
  405.     {
  406.       option_index = indfound;
  407.       optind++;
  408.       if (*s)
  409.         {
  410.           /* Don't test has_arg with >, because some C compilers don't
  411.          allow it to be used on enums.  */
  412.           if (pfound->has_arg)
  413.         optarg = s + 1;
  414.           else
  415.         {
  416.           if (opterr)
  417.             {
  418.               if (argv[optind - 1][1] == '-')
  419.             /* --option */
  420.             fprintf (stderr,
  421.                  "%s: option `--%s' doesn't allow an argument\n",
  422.                  argv[0], pfound->name);
  423.               else
  424.             /* +option or -option */
  425.             fprintf (stderr,
  426.                  "%s: option `%c%s' doesn't allow an argument\n",
  427.                  argv[0], argv[optind - 1][0], pfound->name);
  428.             }
  429.           nextchar += strlen (nextchar);
  430.           return '?';
  431.         }
  432.         }
  433.       else if (pfound->has_arg == 1)
  434.         {
  435.           if (optind < argc)
  436.         optarg = argv[optind++];
  437.           else
  438.         {
  439.           if (opterr)
  440.             fprintf (stderr, "%s: option `%s' requires an argument\n",
  441.                  argv[0], argv[optind - 1]);
  442.           nextchar += strlen (nextchar);
  443.           return optstring[0] == ':' ? ':' : '?';
  444.         }
  445.         }
  446.       nextchar += strlen (nextchar);
  447.       if (longind != NULL)
  448.         *longind = option_index;
  449.       if (pfound->flag)
  450.         {
  451.           *(pfound->flag) = pfound->val;
  452.           return 0;
  453.         }
  454.       return pfound->val;
  455.     }
  456.       /* Can't find it as a long option.  If this is not getopt_long_only,
  457.      or the option starts with '--' or is not a valid short
  458.      option, then it's an error.
  459.      Otherwise interpret it as a short option.  */
  460.       if (!long_only || argv[optind][1] == '-'
  461. #ifdef GETOPT_COMPAT
  462.       || argv[optind][0] == '+'
  463. #endif                /* GETOPT_COMPAT */
  464.       || my_index (optstring, *nextchar) == NULL)
  465.     {
  466.       if (opterr)
  467.         {
  468.           if (argv[optind][1] == '-')
  469.         /* --option */
  470.         fprintf (stderr, "%s: unrecognized option `--%s'\n",
  471.              argv[0], nextchar);
  472.           else
  473.         /* +option or -option */
  474.         fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  475.              argv[0], argv[optind][0], nextchar);
  476.         }
  477.       nextchar = (char *) "";
  478.       optind++;
  479.       return '?';
  480.     }
  481.     }
  482.  
  483.   /* Look at and handle the next option-character.  */
  484.  
  485.   {
  486.     char c = *nextchar++;
  487.     char *temp = my_index (optstring, c);
  488.  
  489.     /* Increment `optind' when we start to process its last character.  */
  490.     if (*nextchar == '\0')
  491.       ++optind;
  492.  
  493.     if (temp == NULL || c == ':')
  494.       {
  495.     if (opterr)
  496.       {
  497. #if 0
  498.         if (c < 040 || c >= 0177)
  499.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  500.                argv[0], c);
  501.         else
  502.           fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
  503. #else
  504.         /* 1003.2 specifies the format of this message.  */
  505.         fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
  506. #endif
  507.       }
  508.     optopt = c;
  509.     return '?';
  510.       }
  511.     if (temp[1] == ':')
  512.       {
  513.     if (temp[2] == ':')
  514.       {
  515.         /* This is an option that accepts an argument optionally.  */
  516.         if (*nextchar != '\0')
  517.           {
  518.         optarg = nextchar;
  519.         optind++;
  520.           }
  521.         else
  522.           optarg = 0;
  523.         nextchar = NULL;
  524.       }
  525.     else
  526.       {
  527.         /* This is an option that requires an argument.  */
  528.         if (*nextchar != '\0')
  529.           {
  530.         optarg = nextchar;
  531.         /* If we end this ARGV-element by taking the rest as an arg,
  532.            we must advance to the next element now.  */
  533.         optind++;
  534.           }
  535.         else if (optind == argc)
  536.           {
  537.         if (opterr)
  538.           {
  539. #if 0
  540.             fprintf (stderr, "%s: option `-%c' requires an argument\n",
  541.                  argv[0], c);
  542. #else
  543.             /* 1003.2 specifies the format of this message.  */
  544.             fprintf (stderr, "%s: option requires an argument -- %c\n",
  545.                  argv[0], c);
  546. #endif
  547.           }
  548.         optopt = c;
  549.         if (optstring[0] == ':')
  550.           c = ':';
  551.         else
  552.           c = '?';
  553.           }
  554.         else
  555.           /* We already incremented `optind' once;
  556.          increment it again when taking next ARGV-elt as argument.  */
  557.           optarg = argv[optind++];
  558.         nextchar = NULL;
  559.       }
  560.       }
  561.     return c;
  562.   }
  563. }
  564.  
  565. int
  566. getopt (
  567.      int argc,
  568.      char *const *argv,
  569.      const char *optstring)
  570. {
  571.   return _getopt_internal (argc, argv, optstring,
  572.                (const struct option *) 0,
  573.                (int *) 0,
  574.                0);
  575. }
  576.  
  577. #ifdef TEST
  578.  
  579. /* Compile with -DTEST to make an executable for use in testing
  580.    the above definition of `getopt'.  */
  581.  
  582. int
  583. main (argc, argv)
  584.      int argc;
  585.      char **argv;
  586. {
  587.   int c;
  588.   int digit_optind = 0;
  589.  
  590.   while (1)
  591.     {
  592.       int this_option_optind = optind ? optind : 1;
  593.  
  594.       c = getopt (argc, argv, "abc:d:0123456789");
  595.       if (c == EOF)
  596.     break;
  597.  
  598.       switch (c)
  599.     {
  600.     case '0':
  601.     case '1':
  602.     case '2':
  603.     case '3':
  604.     case '4':
  605.     case '5':
  606.     case '6':
  607.     case '7':
  608.     case '8':
  609.     case '9':
  610.       if (digit_optind != 0 && digit_optind != this_option_optind)
  611.         printf ("digits occur in two different argv-elements.\n");
  612.       digit_optind = this_option_optind;
  613.       printf ("option %c\n", c);
  614.       break;
  615.  
  616.     case 'a':
  617.       printf ("option a\n");
  618.       break;
  619.  
  620.     case 'b':
  621.       printf ("option b\n");
  622.       break;
  623.  
  624.     case 'c':
  625.       printf ("option c with value `%s'\n", optarg);
  626.       break;
  627.  
  628.     case '?':
  629.       break;
  630.  
  631.     default:
  632.       printf ("?? getopt returned character code 0%o ??\n", c);
  633.     }
  634.     }
  635.  
  636.   if (optind < argc)
  637.     {
  638.       printf ("non-option ARGV-elements: ");
  639.       while (optind < argc)
  640.     printf ("%s ", argv[optind++]);
  641.       printf ("\n");
  642.     }
  643.  
  644.   exit (0);
  645. }
  646.  
  647. #endif /* TEST */
  648.